package cn.hwadee.muying.commons.mail.receiver;

import cn.hwadee.muying.constant.ConstantReplyStatus;
import cn.hwadee.muying.entity.Mail;
import cn.hwadee.muying.entity.MailMessage;
import cn.hwadee.muying.entity.SyncTime;
import com.sun.mail.pop3.POP3Folder;
import org.apache.log4j.Logger;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @描述: 搜狐邮箱邮件接收器
 * @作者: Jing
 * @日期: 2018/1/26
 */
public class SohuReceiver extends AbstractReceiver {

    private Logger log = Logger.getLogger(Receiver.class);

    public SohuReceiver(Mail _mail){
        super(_mail);
    }

    @Override
    public List<MailMessage> fetch(SyncTime syncTime) throws Exception{
        List<MailMessage> mailMessages = new ArrayList<>();
        Properties props = new Properties();
        initProperties(props);

        Session session = Session.getInstance(props);
        Store store  = session.getStore(mail.getRecMailSetting().getProtocol());
        if(!tryConnect(store,mail)){
            throw new RuntimeException("接收邮件失败!");
        }
        String folderName = "INBOX";
        POP3Folder folder = (POP3Folder) store.getFolder(folderName);
        folder.open(Folder.READ_ONLY);

        Instant instant = null;
        if(syncTime != null && syncTime.getSyncTime() != null){
            instant = syncTime.getSyncTime().toInstant();
        }else {
            instant = Instant.now().minus(2, ChronoUnit.DAYS);
        }

        Message[] messages = folder.getMessages();
        int count=0;
        for (Message message:messages) {
            MimeMessage msg = (MimeMessage) message;
            if(msg.getSentDate().toInstant().isBefore(instant)){
                break;
            }
            InternetAddress from = (InternetAddress) msg.getFrom()[0];
            if(!from.getAddress().endsWith(TARGET_ADDRESS)){ //判断是否为目标邮箱
                continue;
            }
            log.info(mail.getEmail()+"正在接收第"+count+"封邮件"+"邮件主题信息"+msg.getSubject()+"邮件发送日期:"+msg.getSentDate()+"邮件来源"+msg.getFrom());
            MailMessage mailMessage = new MailMessage();
            mailMessage.setBuyerEmail(from.getAddress());
            mailMessage.setSubject(msg.getSubject());
            mailMessage.setSentTime(msg.getSentDate());
            mailMessage.setUid(folder.getUID(msg));
            //获取并解析邮件内容
            StringBuffer content = new StringBuffer();
            try{
                getMailTextContent(msg,content);
                parseContent(content.toString(), mailMessage);
            }catch (Exception e){
                log.error(mail.getEmail()+"解析邮件出错:");
                log.error("邮件主题:"+msg.getSubject());
                log.error("邮件发送时间:"+msg.getSentDate());
                e.printStackTrace();
            }

            mailMessage.setBizId(mail.getBizId());
            mailMessage.setMailId(mail.getId());
            mailMessage.setMailName(mail.getName());
            mailMessage.setReplyStatus(ConstantReplyStatus.NO_REPLY);
            mailMessages.add(mailMessage);
            count++;
        }

        folder.close(false);
        store.close();

        return mailMessages;
    }



}
